package com.sky.service.common.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.common.DishFlavorMapper;
import com.sky.mapper.common.DishMapper;
import com.sky.mapper.common.SetmealDishMapper;
import com.sky.pojo.Category;
import com.sky.pojo.Dish;
import com.sky.pojo.DishFlavor;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.common.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service

public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private RedisTemplate redisTemplate;



    public void clearCache(String keyPattern){
        Set keys = redisTemplate.keys(keyPattern);
        keys.forEach(key -> redisTemplate.delete(key));
    }
    @Override
    public Result<String> save(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.save(dish);
        dishDTO.getFlavors().forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
        dishFlavorMapper.BatchSave(dishDTO.getFlavors());

        clearCache("dish:categoryId:" + dish.getCategoryId());
        return Result.success();
    }


    @Override
    public Result<String> update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        if (dishDTO.getFlavors() != null && !dishDTO.getFlavors().isEmpty()) {
            dishDTO.getFlavors().forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.BatchSave(dishDTO.getFlavors());
        }
        clearCache("dish:categoryId:*");
        return Result.success();
    }


    @Override
    public Result<PageResult> page(Integer categoryId, Integer page, Integer pageSize, String name, Integer status) {
        PageHelper.startPage(page, pageSize);
        Page<DishVO> pages = dishMapper.page(categoryId, name, status);
        PageResult pageResult = new PageResult(pages.getTotal(), pages.getResult());
        return Result.success(pageResult);
    }

    @Override
    public Result<String> deleteByIds(Long[] ids) {
        //        1.先判断删除的菜品中是否存在起售的
        Integer dishCount = dishMapper.selectDishCountByIdsAndStatus(List.of(ids), StatusConstant.ENABLE);
        if (dishCount > 0) {
            throw new DeletionNotAllowedException("删除的菜品中包含启售中的");
        }
//        2.判断删除的菜品中是否有被套餐引用的
        Integer setmealCount = setmealDishMapper.selectSetmealCountByDishId(List.of(ids));
        if (setmealCount > 0) {
            throw new DeletionNotAllowedException("删除的菜品中包含被套餐引用的");
        }
        dishMapper.deleteByIds(ids);
        dishFlavorMapper.deleteByIds(ids);

        clearCache("dish:categoryId:*");
        return Result.success();

    }

    @Override
    public List<Dish> list(Integer categoryId) {

        List<Dish> list = dishMapper.list(categoryId);
        return list;
    }

    @Override
    public Result<DishVO> getById(Long id) {
        DishVO dishVO = dishMapper.getById(id);
        dishVO.setFlavors(dishFlavorMapper.list(id));
        return Result.success(dishVO);
    }

    @Override
    public Result<String> startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(BaseContext.getCurrentId())
                .build();
        dishMapper.update(dish);
        clearCache("dish:categoryId:*");
        return Result.success();
    }


    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<DishVO> dishVOList = (List<DishVO>) redisTemplate.opsForValue().get("dish:categoryId:" + dish.getCategoryId());
        if (dishVOList != null && dishVOList.size() > 0) {
            return dishVOList;
        }
        List<Dish> dishList = dishMapper.list1(dish);
        dishVOList = new ArrayList<>();
        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);
            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());
            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        redisTemplate.opsForValue().set("dish:categoryId:" + dish.getCategoryId(), dishVOList);
        return dishVOList;
    }
}
